package com.ml.nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChannel案例3-使用一个Buffer完成文件读取。
 * 实例要求:
 * 1) 使用 FileChannel(通道) 和 方法 read , write，完成文件的拷贝
 * 2) 拷贝一个文本文件 1.txt , 放在项目下即可
 *
 * @author xr-8
 * @date 2022-01-08
 * @time 23:18
 */
public class FileChannel03 {

    public static void main(String[] args) throws IOException {
        WhileRead();
        AllRead();
    }

    /**
     * 可以重复利用一小块缓存，节省内存空间
     *
     * @throws IOException
     */
    private static void WhileRead() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("G://1.txt");
        FileChannel fileChannel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("./1copy.txt");
        FileChannel fileChannel1 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(5);
        while (true) { //循环读取
            byteBuffer.clear();//清空buffer
            int read = fileChannel.read(byteBuffer);
            System.out.println("read=" + read);
            System.out.println("limit=" + byteBuffer.limit());
            System.out.println("position=" + byteBuffer.position());
            if (read == -1) { //表示读完
                break;
            }
            //将buffer 中的数据写入到 1copy.txt
            byteBuffer.flip();
            fileChannel1.write(byteBuffer);
        }
        //关闭相关的流
        fileOutputStream.close();
        fileInputStream.close();
    }

    /**
     * 一次性全部读取，适合小文件
     *
     * @throws IOException
     */
    private static void AllRead() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("G://1.txt");
        FileChannel fileChannel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("./1copy.txt");
        FileChannel fileChannel1 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size());
        fileChannel.read(byteBuffer);

        byteBuffer.flip();
        fileChannel1.write(byteBuffer);

        fileOutputStream.close();
        fileInputStream.close();
    }
}
